<?php

namespace app\common\controller;
include_once $_SERVER["DOCUMENT_ROOT"].'/../application/admin/common.php';
use app\admin\model\User;
use app\common\library\Auth;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;



/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    private $appid = 'wx2bab6cd1400f48bb';
    private $secret = '2c4eec8b958e7be9c627ac1f369663de';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        // 添加调试日志
        if (isset($_GET['XDEBUG_SESSION_START']) || config('app_debug')) {
            error_log("Api基类 _initialize 开始执行 - " . date('Y-m-d H:i:s'));
            error_log("请求URI: " . ($_SERVER['REQUEST_URI'] ?? 'null'));
            error_log("Authorization头: " . ($_SERVER['HTTP_AUTHORIZATION'] ?? 'null'));
        }

        try {
            //跨域请求检测
            check_cors_request();

            // 检测IP是否允许
            check_ip_allowed();

            //移除HTML标签
            $this->request->filter('trim,strip_tags,htmlspecialchars');

            $this->auth = Auth::instance();

            $modulename = $this->request->module();
            $controllername = Loader::parseName($this->request->controller());
            $actionname = strtolower($this->request->action());

            if (isset($_GET['XDEBUG_SESSION_START']) || config('app_debug')) {
                error_log("模块: $modulename, 控制器: $controllername, 方法: $actionname");
            }

            $this->auth->init();
            // 加载当前控制器语言包
            $this->loadlang($controllername);

            if (isset($_GET['XDEBUG_SESSION_START']) || config('app_debug')) {
                error_log("Api基类 _initialize 完成 - " . date('Y-m-d H:i:s'));
            }
        } catch (\Exception $e) {
            error_log("Api基类 _initialize 失败: " . $e->getMessage() . " - " . date('Y-m-d H:i:s'));
            error_log("错误堆栈: " . $e->getTraceAsString());
            throw $e;
        }
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = Loader::parseName($name);
        $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
        $lang = $this->request->langset();
        $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 200, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为400
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }


    public static function errinfo($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        // 检查是否是HttpResponseException的消息，如果是则不处理
        if (strpos($msg, 'HttpResponseException') !== false) {
            return;
        }

        switch ($msg) {
            case 'Wrong number of segments':
                $msg = __('过期的Token，请重新登录！');
                break;
            case 1002:
                $msg = __('Token has expired');
                break;
        }
        $data=array("code"=>$code,"msg"=>$msg, "data"=>$data, "type"=>$type, "header"=>$header);
        echo json_encode($data);
        exit;
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则使用默认类型判断
        $type = $type ? : $this->responseType;

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $result['code'] = $code;
        echo json_encode($result);exit;
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method  前置操作方法名
     * @param array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     * @param mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }

    protected function UserFilter($user)
    {
        $newuser = [];
        $newuser['id'] = $user['id'];
        $newuser['openid'] = $user['openid'];
        $newuser['group_id'] = $user['group_id'];
        $newuser['username'] = $user['username'];
        $newuser['nickname'] = $user['nickname'];
        $newuser['email'] = $user['email'];
        $newuser['mobile'] = $user['mobile'];
        $newuser['avatar'] = $user['avatar'];
        $newuser['gender'] = $user['gender'];
        $newuser['birthday'] = $user['birthday'];
        $newuser['latitude'] = $user['latitude'];
        $newuser['longitude'] = $user['longitude'];
        $newuser['address'] = $user['address'];
        $newuser['money'] = $user['money'];
        $newuser['city_id'] = $user['city_id'];
        $newuser['city_id'] = $user['city_id'];
        return $newuser;
    }

    protected function get_wx_mobile($code)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        if (isset($result['errcode'])) {
            return [
                'code' => 1,
                'msg' => '获取 access_token 失败: ' . $result['errmsg']
            ];
        }
        $access_token = $result['access_token'];
        // 拼接微信手机号的 URL
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";//&openid={$user['oid']}
        // 发送 HTTP 请求
        // 准备 POST 数据
        $postData = json_encode(['code' => $code]);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $response = curl_exec($ch);
        curl_close($ch);
        // 解析返回的 JSON 数据
        $result = json_decode($response, true);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            return [
                'code' => $result['errcode'],
                'msg' => $result['errmsg'],
            ];
        }
        $phone_info = $result['phone_info'];
        $mobile = $phone_info['phoneNumber'];
        return $mobile;
    }

    public function get_wx_openid($code)
    {
        // 拼接微信登录接口的 URL
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($response, true);
//        $result=array(
//            "openid"=>"xxxxxx",
//            "session_key"=>"xxxxx",
//            "unionid"=>"xxxxx",
//            "errcode"=>0,
//            "errmsg"=>"xxxxx"
//        );
//        $response = json_encode($result);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            // 处理错误
            return [
                'code' => $result['errcode'],
                'msg' => $result['errmsg']
            ];
        }

        // 解析返回的 JSON 数据
        $result = json_decode($response, true);

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            return [
                'code' => $result['errcode'],
                'msg' => $result['errmsg']
            ];
        }

        if ($result == null) {
            return [
                'code' => 0,
                'msg' => '连接失败'
            ];
        }
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        $unionid = "";
        if (isset($result['unionid'])) {
            $unionid = $result['unionid'];
        } else {
            $unionid = "";
        }
        return array("openid"=>$openid,"session_key"=>$session_key,"unionid"=>$unionid);
    }

    public function generateQrcode($id, $name='', $type = 3)
    {
        // 验证参数
        if (empty($id)){
            $this->error('ID不能为空');
        }

        // 生成二维码内容（JSON格式）
        $qrContent = json_encode([
            'action' => '/api/qrcode/scan',
            'params' => [
                'school_id'   => (int)$id,
                'school_name' => htmlspecialchars($name),
                'type'        => in_array($type, [1,2,3]) ? $type : 3
            ]
        ]);

        try {
            $result = Builder::create()
                ->data($qrContent)
                ->encoding(new Encoding('UTF-8'))
                ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                ->size(300)
                ->build();

            $base64 = 'data:image/png;base64,' . base64_encode($result->getString());
            return $base64;

        } catch (\Exception $e) {
            $this->error('二维码生成失败: ' . $e->getMessage());
        }
        exit;
    }
}
